<?php

/**
 * @author Archer
 * @note Http响应处理
 * @mail 188802862@qq.com
 */

namespace console\http;

use console\core\manager\InstanceManager;

class Response extends InstanceManager
{

    //定义公共错误码以及项目错误码
    private static $baseCode = [] , $itemCode = [];

    //json格式返回数据
    static function json($code = 0 , $msg = '' ,array $res = [])
    {
        if(empty($msg) && empty($res))
            return self::jsonByCode($code);
        return self::jsonByNorm($code,$msg,$res);
    }

    //根据Code 筛选错误码并返回对应信息
    private static function jsonByCode($code = 0)
    {
        //是否已定义项目
        if(defined('ITEM_NAME') && !self::$itemCode)
            self::$itemCode = \console\Config::loadItem('code',true);

        //是否已存在公用错误码
        if(!self::$baseCode)
            self::$baseCode = \console\Config::loadBase('code',true);

        //传递错误码是否存在于公用容器
        if(self::$baseCode && array_key_exists($code,self::$baseCode))
            return self::jsonByNorm($code,self::$baseCode[$code]);

        //传递错误码是否存在于项目容器
        if(self::$itemCode && array_key_exists($code,self::$itemCode))
            return self::jsonByNorm($code,self::$baseCode[$code]);

        //获得默认错误码
        $code = \console\Config::loadBase('config',true)['default']['errCode'];

        //未找到对应错误码信息 返回默认信息
        return self::jsonByNorm($code,self::$baseCode['e_'.$code]);
    }

    //定义返回格式
    private static function jsonByNorm($code = 0, $msg = '' , $res = [])
    {
        return self::Response()->setJsonContent([
            'err'=>$code,
            'msg'=>$msg?:'未知错误 - Sorry.',
            'res'=>$res
        ])->getContent();
    }
}